package com.edu.marker.http;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;


import android.net.Proxy;
import android.text.TextUtils;

public class EHttpClient {

	private static final String TAG = EHttpClient.class.getSimpleName();
	private static final String WARNING_REINIT_CONFIG = "ServiceClient configuration " +
			"had already been initialized before. ";
	// private static final String ERROR_NOT_INIT =
	// "SFHttpClient must be init with configuration before using";
	private static final String ERROR_INIT_CONFIG_NULL = "ServiceClient configuration " +
			"can not be initialized with null";

	private EHttpConfigs mConfiguration;
	
	public static String mCookie;

	private volatile static EHttpClient instance;

	/** Returns singleton class instance */
	public static EHttpClient getInstance() {
		if (instance == null) {
			synchronized (EHttpClient.class) {
				if (instance == null) {
					instance = new EHttpClient();
				}
			}
		}
		return instance;
	}

	private EHttpClient() {
	}

	public synchronized void init(EHttpConfigs configuration) {
		if (configuration == null) {
			throw new IllegalArgumentException(ERROR_INIT_CONFIG_NULL);
		}

		if (this.mConfiguration == null) {
			this.mConfiguration = configuration;
		} else {
			android.util.Log.w(TAG, WARNING_REINIT_CONFIG);
		}
	}

	// *****************************************************
	// *
	// * get the HttpClient instance
	// *
	// *****************************************************

	public HttpClient getHttpClient() {
		return this.mConfiguration.mHttpClient;
	}

	// *****************************************************
	// *
	// * execute http get or post method to the server
	// *
	// *****************************************************

	public void execute(ERequest request, EResponse response,
			List<BasicNameValuePair> params, ERequest.RequestType reqType)
			throws EHttpException {
		try {
			HttpUriRequest req = request.handleRequeste();
			executeRequest(req, response, params, reqType);
		} catch (IOException e) {
			throw new EHttpException(1, "Network IO exception", e);
		}
	}

	private void executeRequest(HttpUriRequest req, EResponse resp,
			List<BasicNameValuePair> params, ERequest.RequestType reqType)
			throws IOException {
		HttpEntity entity = null;
		try {
			checkWapProxyNeed();

			if (reqType == ERequest.RequestType.API_POST) {
				((HttpPost) req).setEntity(new UrlEncodedFormEntity(params,
						"UTF_8"));
				
				System.out.println("=========="+params);
			}
			
			HttpResponse response = this.mConfiguration.mHttpClient
					.execute(req);
			//mCookie = getCookie((DefaultHttpClient) this.mConfiguration.mHttpClient);
			if (response.getStatusLine().getStatusCode() == 200) {
				System.out.println("=======######==");
				entity = response.getEntity();
				InputStream in = entity.getContent();
//				resp.handleReponse(EHttpUtils.stream2String(in));
				resp.handleReponse(in);
			} else {
				System.out.println("==========");
				req.abort();
			}
		} finally {
			if (entity != null)
				entity.consumeContent();
		}
	}
	
	private String getCookie(DefaultHttpClient httpClient) {
        List<Cookie> cookies = httpClient.getCookieStore().getCookies();
        StringBuilder sb = new StringBuilder();
        final int size = cookies.size();
        for (int i = 0; i < size; i++) {
            Cookie cookie = cookies.get(i);
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            if (!TextUtils.isEmpty(cookieName)
                     && !TextUtils.isEmpty(cookieValue)) {
                sb.append(cookieName + "=" );
                break;
           }
       }
       return sb.toString();
  }

	private boolean isWapNetwork() {
		final String proxyHost = android.net.Proxy.getDefaultHost();
		return !TextUtils.isEmpty(proxyHost);
	}

	private void checkWapProxyNeed() {
		if (!EHttpUtils.isWifiAvailable(this.mConfiguration.mContext)
				&& isWapNetwork()) {
			final HttpHost host = (HttpHost) this.mConfiguration.mHttpClient
					.getParams().getParameter(ConnRouteParams.DEFAULT_PROXY);
			if (host == null) {
				final String defaultHost = Proxy.getDefaultHost();
				int port = Proxy.getDefaultPort();
				HttpHost httpHost = new HttpHost(defaultHost, port);
				this.mConfiguration.mHttpClient.getParams().setParameter(
						ConnRouteParams.DEFAULT_PROXY, httpHost);
			}
		} else {
			final HttpHost host = (HttpHost) this.mConfiguration.mHttpClient
					.getParams().getParameter(ConnRouteParams.DEFAULT_PROXY);
			if (host != null) {
				this.mConfiguration.mHttpClient.getParams().removeParameter(
						ConnRouteParams.DEFAULT_PROXY);
			}
		}
	}
}
